<script setup>
import axios from 'axios'
import { ref, onMounted } from 'vue'

const items = [
  {
    title: 'DEV(默认数码银狐)',
    env: 'dev',
    host: 'https://dev-hdsaas.facehand.cn/',
    account: 'yhj',
    password: '86a572af9a60576a8a8824c43385b806',
    corpId: "150000000",
    wxCorpId: "wpc7diCwAAI0KNCMvlAbcB4xslzyzS8Q",
  },
  {
    title: 'FAT(默认金堂)',
    env: 'fat',
    host: 'https://fat-hdsaas.facehand.cn/',
    account: 'lixiao',
    password: 'e10adc3949ba59abbe56e057f20f883e',
    corpId: "150007745",
    wxCorpId: "wpc7diCwAAiaTTafQCtv7InNcTHq3IJQ",
  }
]


const formInfo = ref(items.map(item => ({ corpNo: item.corpId, keyword: '', errorInfo: '' })))

onMounted(() => {
  const lastInfo = localStorage.getItem('last_formInfo')
  if (lastInfo) {
    formInfo.value = JSON.parse(lastInfo)
  }
})

const getToken = async (item, index, client) => {
  if (!formInfo.value[index].keyword) {
    formInfo.value[index].errorInfo = '请输入登录职员姓名'
    return
  }
  try {
    const { env, host, account, password, wxCorpId, corpId: defaultCorpId } = item
    const corpId = formInfo.value[index].corpNo || defaultCorpId
    const cache = localStorage.getItem(`${env}_${corpId}_${formInfo.value[index].keyword}`)
    const wxUserIds = JSON.parse(localStorage.getItem(`${env}_${corpId}_wx_user_id`) ?? '{}')
    const tokenCache = cache ? JSON.parse(cache) : {}
    let token = tokenCache?.token
    if (+new Date() >= (tokenCache?.expired ?? 0)) {
      let wxUserId = wxUserIds[formInfo.value[index].keyword]
      if (!wxUserId) {
        const loginInfo = await axios({
          url: `${host}gateway/saas-operate-service/api/v1/operate/login`,
          method: 'post',
          data: {
            account,
            password
          }
        })

        const loginToken = loginInfo.data.data.token
        const listData = await axios({
          url: `${host}gateway/saas-operate-service/api/v1/integration/staffer/list`,
          method: 'get',
          headers: {
            operate: loginToken
          },
          params: {
            corpId,
            keyName: formInfo.value[index].keyword,
            pageNum: 1,
            pageSize: 30
          }
        })
        const user = listData.data.data.list.find(i => i.name === formInfo.value[index].keyword)
        if (user) {
          wxUserId = user.wxUserId
        } else {
          throw new Error('登录失败')
        }
      }
      const res = await axios({
        url: `${host}gateway/saas-operate-service/api/v1/operate/system_login`,
        method: 'get',
        params: {
          wxCorpId,
          wxUserId,
          corpId
        }
      })
      const data = res?.data?.data
      if (data) {
        formInfo.value[index].errorInfo = ''
        token = data
        localStorage.setItem('last_formInfo', JSON.stringify(formInfo.value))

        localStorage.setItem(`${env}_${corpId}_wx_user_id`, JSON.stringify({ ...wxUserIds, [formInfo.value[index].keyword]: wxUserId }))
        localStorage.setItem(`${env}_${corpId}_${formInfo.value[index].keyword}`, JSON.stringify({ token: data, expired: +new Date() + 1000 * 60 * 60 * 12 }))
      } else {
        throw new Error('登录失败')
      }
    }
    formInfo.value[index].errorInfo = ''
    localStorage.setItem('last_formInfo', JSON.stringify(formInfo.value))
    chrome.tabs.create({ url: `${host}${client}/?token=${token}` });
  } catch (error) {
    console.error('error', error)
    formInfo.value[index].errorInfo = `没找到这个职员`
  }
}
</script>

<template>
  <div v-for="(item, index) in items" class="item-box" :key="index">
    <div class="title">{{ item.title }}</div>
    <div style="margin-bottom: 15px; display: flex; flex-direction: column;">
      <input style="height: 30px;padding: 4px;margin-bottom: 6px;" type="text" v-model="formInfo[index].corpNo"
        placeholder="企业编号(可不填)" />
      <input style="height: 30px;padding: 4px;" type="text" v-model="formInfo[index].keyword" placeholder="登录职员姓名" />
      <div v-if="formInfo[index].errorInfo" style="color: red;font-size: 16px;">{{ formInfo[index].errorInfo }}</div>
    </div>
    <div style="display: flex; flex-direction: row;">
      <div class="btn blue" @click="getToken(item, index, 'pmweb')">PC</div>
      <div class="btn peru" @click="getToken(item, index, 'dhwap')">H5</div>
    </div>
  </div>
</template>

<style scoped>
.item-box {
  border: 1px solid gray;
  padding: 4px;
}

.item-box:not(:last-child) {
  margin-bottom: 15px;
}

.title {
  font-size: 18px;
  margin-bottom: 4px;
}

.btn {
  width: 88px;
  height: 40px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #fff;
}

.red {
  background-color: rgb(233, 7, 7);
}

.peru {
  background-color: rgb(7, 199, 233);
}

.blue {
  background-color: #1447ff;
  margin-bottom: 10px;
  margin-right: 8px;
}
</style>
